package com.nondo.rdp.finance.service.impl.course;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.finance.domain.course.SectionProcess;
import com.nondo.rdp.finance.repository.course.SectionProcessRepository;
import com.nondo.rdp.finance.service.course.SectionProcessService;

@Transactional
@Service
public class SectionProcessServiceImpl implements SectionProcessService {
    @Autowired
    SectionProcessRepository sectionProcessRepository;

    @Override
    public SectionProcess findOne(Long id) {
        return this.sectionProcessRepository.findOne(id);
    }
    
    @Override
    public SectionProcess getOne(Long sid, Long uid) {
        return this.sectionProcessRepository.getOne(sid ,uid);
    }

    @Override
    public SectionProcess save(SectionProcess sectionProcess) {
        return this.sectionProcessRepository.save(sectionProcess);
    }
    
    @Override
    public Page<SectionProcess> findAll(Page<SectionProcess> page, SectionProcess sectionProcess) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<SectionProcess> dictPage = sectionProcessRepository.findAll((root, query, builder) -> {
        	List<Predicate> predicates = new ArrayList<>();
        	if (sectionProcess != null) {
        		predicates.add(builder.equal(root.get("user").get("id"), sectionProcess.getUser().getId()));
        		predicates.add(builder.equal(root.get("courseId"), sectionProcess.getCourseId()));
        	}
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
        	
            return builder.and(predicatesArray);
        	
        }, pageRequest);

        return new Page<SectionProcess>(dictPage);
    }

}